package com.dingpeikeji.quickdeer.modules.realsche.service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.modules.orders.dao.TOrdersDao;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.realsche.entity.TRealsche;
import com.dingpeikeji.quickdeer.core.modules.site.entity.TSitedtl;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.modules.realsche.dao.FRealscheDao;
import com.dingpeikeji.quickdeer.modules.rentproduct.dao.TDemandsDao;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.DemandsReact;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TDemands;
import com.google.common.collect.Maps;

/**
 * 
 * 预定线路
 * @author wuhao
 *
 */
@Service
@Transactional(readOnly = true)
public class FRealscheService {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private FRealscheDao fRealscheDao; // 预定线路DAO
	@Autowired
	private TSitedtlService tSitedtlService; // 站点DAO
	@Autowired
	private TOrdersDao orderDao; // 订单DAO
	@Autowired
	private TDemandsDao demandDao;
	
	/**
	 * 分页查询实际班次列表
	 * @param page
	 * @param realsche
	 * @return
	 */
	public Page<TRealsche> findPage(Page<TRealsche> page, TRealsche realsche) {
		realsche.setPage(page);
		List<TRealsche> realscheList = fRealscheDao.findList(realsche);
		page.setList(realscheList);
		return page;
	}
	
	/**
	 * 实际班次查询
	 * @param realsche
	 * @return
	 */
	public List<TRealsche> findRealscheList(TRealsche realsche) {
		return fRealscheDao.findList(realsche);
	}
	
	/**
	 * 查询所有的景点
	 * @return
	 */
	public List<TSitedtl> findAllSite(){
		List<TSitedtl> siteList = tSitedtlService.findList(new TSitedtl());
		return siteList;
	}
	
	/**
	 * 根据实际班次主键获取实际班次的完整信息，包括上客点、下客点以及余票
	 * @param realscheid 实际班次主键
	 * @return
	 */
	public TRealsche getRealscheOrderById(TRealsche realsche){
		TRealsche realsche2 = fRealscheDao.getRealscheOrderById(realsche);
		return realsche2;
	}
	
	public TOrders getOrders(String orderid){
		return orderDao.get(orderid);
	}
	
	/**
	 * 保存订单信息
	 * @param orders
	 */
	public String saveOrder(TOrders orders, TRealsche realsche){
		String message = null;
		orders.setOrderstatus(TOrders.STATUS_NO_PAY); // 未支付
		orders.setCreateDate(new Date()); // 创建时间
		// 计算应付金额
		Double retailPrice = Double.valueOf(StringUtils.isEmpty(realsche.getRetailprice())?"0":realsche.getRetailprice());
		Integer purchasenum = Integer.valueOf(StringUtils.isEmpty(orders.getPurchasenum())?"0":orders.getPurchasenum());
		Integer childnum = Integer.valueOf(StringUtils.isEmpty(orders.getChildnum())?"0":orders.getChildnum());
		orders.setDueamount(""+(purchasenum*retailPrice+childnum*retailPrice/2));
		Map<String,Object> param = Maps.newHashMap();
		param.put("realscheid", orders.getRealscheid());
		param.put("ordertype", orders.getOrdertype());
		param.put("purchasenum", orders.getPurchasenum());
		param.put("childnum", orders.getChildnum());
		param.put("dueamount", orders.getDueamount());
		param.put("orderuserid", orders.getOrderuserid());
		param.put("payway", orders.getPayway());
		param.put("realboardid", realsche.getRealboardid());
		param.put("realoffid", realsche.getRealoffid());
		param.put("contacts", orders.getContacts());
		param.put("payertel", orders.getPayertel());
		fRealscheDao.proOrders(param);
		Integer returnflag = (Integer) param.get("returnflag");
		if(returnflag!=null&&returnflag==-1){
			message = (String) param.get("returnmsg");
		} else {
			orders.setOrderid((String) param.get("orderid"));
		}
		return message;
	}
	
	/**
	 * 分页查询订单列表
	 * @param page
	 * @param orders
	 * @return
	 */
	public Page<TOrders> findOrderPage(Page<TOrders> page, TOrders orders) {
		if(StringUtils.isEmpty(orders.getCreateDateQueryStart()) &&
				StringUtils.isEmpty(orders.getCreateDateQueryEnd())){
			Calendar cal = Calendar.getInstance();
			orders.setCreateDateQueryEnd(DateUtils.formatDate(cal.getTime()));
			cal.set(Calendar.DATE, cal.get(Calendar.DATE) - 7);
			orders.setCreateDateQueryStart(DateUtils.formatDate(cal.getTime()));
		}
		orders.setPage(page);
		List<TOrders> realscheList = fRealscheDao.findOrderWithRealscheList(orders);
		page.setList(realscheList);
		return page;
	}
	public Page<TOrders> findOrderPageForMobile(Page<TOrders> page, TOrders orders) {
		orders.setPage(page);
		List<TOrders> realscheList = fRealscheDao.findOrderWithRealscheList(orders);
		page.setList(realscheList);
		return page;
	}
	
	/**
	 * 订单查询
	 * @return
	 */
	public List<TOrders> getOrdersList(TOrders orders){
		return fRealscheDao.findOrderWithRealscheList(orders);
	}
	
	/**
	 * 取消订单
	 * @param orders
	 * @return
	 */
	public boolean changeOrdersStatus(TOrders orders){
		if(fRealscheDao.changeOrdersStatus(orders)>0){
			return true;
		}
		return false;
	}
	
	/**
	 * 取消票
	 * @param orders
	 * @return
	 */
	public String cancelOrder(TOrders orders ,String cancelid){
		String message = null;
		Map<String,Object> param = Maps.newHashMap();
		param.put("orderid", orders.getOrderid());
		param.put("cancelid", cancelid);
		fRealscheDao.cancelOrder(param);
		Integer returnflag = (Integer) param.get("returnflag");
		if(returnflag!=null&&returnflag==-1){
			message = (String) param.get("returnmsg");
		}
		return message;
	}
	
	/**
	 * 退票
	 * @param orders
	 * @return
	 */
	public Map<String,Object> proCmptReturn(TOrders orders){
		Map<String,Object> param = Maps.newHashMap();
		param.put("orderid", orders.getOrderid());
		param.put("rtnadult", orders.getPurchasenum());
		param.put("rtnchild", orders.getChildnum());
		fRealscheDao.proCmptReturn(param);
		return param;
	}
	
	/**
	 * 完成退票
	 * @param orders
	 * @return
	 */
	public Map<String,Object> proConfirmRtn(String batchNo){
		Map<String,Object> param = Maps.newHashMap();
		param.put("batch_no", batchNo);
		fRealscheDao.proConfirmRtn(param);;
		return param;
	}
	
	/**
	 * 完成退票
	 * @param orders
	 * @return
	 */
	public Map<String,Object> proConfirmSysRtn(Integer outid, String settlereason){
		Map<String,Object> param = Maps.newHashMap();
		param.put("outid", outid);
		param.put("settlereason", settlereason);
		fRealscheDao.proConfirmSysRtn(param);;
		return param;
	}
	
	/**
	 * 更换车队
	 * @param orders
	 * @return
	 */
	public Map<String,Object> proConfirmChgBus(Integer orderid, String settlereason){
		Map<String,Object> param = Maps.newHashMap();
		param.put("orderid", orderid);
		param.put("settlereason", settlereason);
		fRealscheDao.proConfirmChgBus(param);;
		return param;
	}	
	
	/**
	 * 支付回调
	 * @param orders
	 * @return
	 */
	@Transactional(readOnly = false)
	public Map<String,Object> proConfirmPay(Integer orderid, Double payfee, String flowno, String buyerno, String payway){
		Map<String,Object> param = Maps.newHashMap();
		try {
			param.put("orderid", orderid);
			param.put("payfee", payfee);
			param.put("flowno", flowno);
			param.put("buyerno", buyerno);
			param.put("payway", payway);
			fRealscheDao.proConfirmPay(param);
			// 在存储过程中加了这段逻辑
			/*TOrders orders = orderDao.get(""+orderid);
			if(orders.getOrdertype().equals(TOrders.ORDER_TYPE_RENTPRODUCT_CUSTOM)){
				DemandsReact dr = demandDao.getDemandsReact(Integer.parseInt(orders.getRealscheid()));
				TDemands demand = demandDao.get(dr.getDemandid()+"");
				demand.setReactstatus(TDemands.REACTSTATUS_DONE);
				demandDao.update(demand);
			}*/
		} catch (Exception e) {
			logger.debug("完成支付调用异常", e);
			throw new RuntimeException();
		}
		return param;
	}
	
	/**
	 * 更新订单信息
	 * @param order
	 */
	public void updateOrder(TOrders order){
		orderDao.update(order);
	}
	
	public boolean delOrder(TOrders order) throws Exception{
		try {
			int num = orderDao.delete(order);
			if(num > 0) {
				return true;
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		return false;
	}

	public void updateOrderOffline(int id, String orderRemarks) {
		orderDao.updateOrderOffline(id,orderRemarks);
	}

	public void save(TOrders orders) {
		orderDao.insert(orders);
	}

	public int selectLastId() {
		return orderDao.selectLastId();
	}

	public void updateOrderById(String payway, String out_trade_no) {
		orderDao.updateOrderById(payway,out_trade_no);
	}
}
